using System;
using System.Collections.Generic;
using Mall.Api.Entity;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using Mall.Api.ParamModel;
using Newtonsoft.Json;
using Mall.Api.Repository;
using Mall.Api.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication;

namespace Mall.Api.Controllers
{
    /// <summary>
    /// 购物车
    /// </summary>
    [Authorize]
    [ApiController]
    [Route("shoppingCart")]
    public class ShoppingCartController : ControllerBase
    {
        private IRepository<Users> _usersRespository;

        private IRepository<Warehouse> _warehouse;
        private IRepository<CommodityWarehouse> _commodityWarehouse;
        private IRepository<CommodityProperty> _commodityProperty;
        private IRepository<CommodityPropertyValue> _commodityPropertyValue;
        private IRepository<CommoditySKU> _commoditySKU;
        private IRepository<Commodity> _commodity;
        private IRepository<ShoppingCart> _shoppingCart;
        private IRepository<UserShoppingTrolley> _userShoppingCart;
        private IRepository<Supplier> _supplier;
        private IRepository<Order> _order;
        private IRepository<UserOrder> _userOrder;
        private IRepository<Payment> _payment;
        private IRepository<OrderStatu> _orderStatu;

        private readonly IConfiguration _configuration;

        public ShoppingCartController(IConfiguration configuration, IRepository<Users> usersRespository, IRepository<Warehouse> warehouse,
        IRepository<CommodityWarehouse> commodityWarehouse, IRepository<CommodityProperty> commodityProperty, IRepository<CommodityPropertyValue> commodityPropertyValue,
        IRepository<CommoditySKU> commoditySKU, IRepository<Commodity> commodity, IRepository<ShoppingCart> shoppingCart, IRepository<UserShoppingTrolley> userShoppingCart,
        IRepository<Supplier> supplier, IRepository<Order> order, IRepository<UserOrder> userOrder, IRepository<Payment> payment,
        IRepository<OrderStatu> orderStatu)
        {
            _configuration = configuration;
            _usersRespository = usersRespository;
            _warehouse = warehouse;
            _commodityWarehouse = commodityWarehouse;
            _commodityProperty = commodityProperty;
            _commodityPropertyValue = commodityPropertyValue;
            _commoditySKU = commoditySKU;
            _commodity = commodity;
            _shoppingCart = shoppingCart;
            _userShoppingCart = userShoppingCart;
            _supplier = supplier;
            _order = order;
            _userOrder = userOrder;
            _payment = payment;
            _orderStatu = orderStatu;

        }

        /// <summary>
        /// 获取购物车信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public dynamic Get()
        {


            var claims = base.HttpContext.AuthenticateAsync().Result
            .Principal.Claims.FirstOrDefault().Subject.Claims;


            var userid = claims.FirstOrDefault(c => c.Type == "id")?.Value;

            var usId = _userShoppingCart.Table.Where(u => u.UsersId == int.Parse(userid)).FirstOrDefault()?.Id;
            if (usId == null)
            {

                var userShoppingCart = new UserShoppingTrolley
                {
                    Users = _usersRespository.Table.Single(u => u.Id == int.Parse(userid)),

                };


                _userShoppingCart.Insert(userShoppingCart);
                usId = userShoppingCart.Id;
            }


            var shoppingInfo = _shoppingCart.Table.Where(s => s.IsDeleted == false && s.UserShoppingTrolleyId == usId).ToList();
            var skuIdList = shoppingInfo.Select(t => t.CommoditySKUId).ToList();
            var skuInfo = _commoditySKU.Table.Where(s => s.IsDeleted == false && skuIdList.Contains(s.Id)).ToList();
            var commodityDetails = new List<CommoditySKU>();
            foreach (var item in shoppingInfo)
            {
                var skutmp = skuInfo.Where(x => x.Id == item.CommoditySKUId).FirstOrDefault();
                commodityDetails.Add(skutmp);

            }





            var commodityCount = (from commodity in commodityDetails
                                  group commodity by new { commodity.CommodityId }
                    into ct
                                  select new { CommodityId = ct.Key.CommodityId }).ToList();

            var commodityProperty = _commodityProperty.Table.Where(c => c.IsDeleted == false);
            var commodityPropertyValue = _commodityPropertyValue.Table.Where(p => p.IsDeleted == false);
            var Info = new List<object>();

            var commodityPropertyValueSkus = from cvs in commodityDetails
                                             join c in _commodity.Table on cvs.CommodityId equals c.Id
                                             join pv in _commodityPropertyValue.Table on cvs.CommodityPropertyValueId equals pv.Id
                                             select new
                                             {
                                                 Id = cvs.Id,
                                                 CommodityId = cvs.CommodityId,
                                                 ProductName = c.ProductName,
                                                 Price = c.Price,
                                                 CoverPictrue = c.CoverPicture,
                                                 CommodityPropertyValueId = cvs.CommodityPropertyValueId,
                                                 CommodityProperty = cvs.CommodityPropertyId,
                                                 PropertyValue = pv.PropertyValue
                                             };

            var shoppingModelList = new List<ShoppingModel>();
            foreach (var comd in commodityCount)
            {
                var CommodityProductValueStr = "";
                var SkuIdStr = "";
                var ProductName = "";
                var CoverPictrue = "";
                var Price = 0.0;
                foreach (var item in commodityPropertyValueSkus)
                {
                    if (comd.CommodityId == item.CommodityId)
                    {
                        ProductName = item.ProductName;
                        Price = item.Price;
                        CoverPictrue = item.CoverPictrue;
                        SkuIdStr += item.Id.ToString() + " ";
                        CommodityProductValueStr += item.PropertyValue + " ";
                    }
                }
                shoppingModelList.Add(new ShoppingModel
                {
                    CommodityId = comd.CommodityId,
                    ProductName = ProductName,
                    Price = Price,
                    CoverPictrue = CoverPictrue,
                    CommodityProductValueStr = CommodityProductValueStr,
                    SkuIds = SkuIdStr.Split(" ")
                });
            }



            return shoppingModelList;




        }






        /// <summary>
        /// 获取我的订单
        /// </summary>
        /// <returns></returns>
        [HttpGet("myorder")]
        public dynamic GetOrder()
        {


            var claims = base.HttpContext.AuthenticateAsync().Result
            .Principal.Claims.FirstOrDefault().Subject.Claims;


            var userid = claims.FirstOrDefault(c => c.Type == "id")?.Value;

            var usId = _userOrder.Table.Where(u => u.UsersId == int.Parse(userid)).ToList();
            //   var shoppingInfo = _order.Table.Where(s => s.IsDeleted == false && usId.Contains(s.UserOrderId)).ToList();

            var shoppingInfo =from uod in _userOrder.Table
                                join od in _order.Table on uod.Id equals od.UserOrderId
                                select new {CommoditySKUId=od.CommoditySKUId};

              

            if (usId == null)
            {
                return new List<ShoppingModel>();
            }

          


            var skuIdList = shoppingInfo.Select(t => t.CommoditySKUId).ToList();
            var skuInfo = _commoditySKU.Table.Where(s => s.IsDeleted == false && skuIdList.Contains(s.Id)).ToList();
            var commodityDetails = new List<CommoditySKU>();
            foreach (var item in shoppingInfo)
            {
                var skutmp = skuInfo.Where(x => x.Id == item.CommoditySKUId).FirstOrDefault();
                commodityDetails.Add(skutmp);

            }


            // var orderInfos = ;

            // var orderInfos = from s in commodityDetails
            //                  join d in _order.Table on s.Id equals d.CommoditySKUId
            //                  join f in _userOrder.Table on d.UserOrderId equals f.Id
            //                  where f.UsersId==int.Parse(userid)
            //                  select new
            //                  {
            //                      Id = s.CommodityId,
            //                      OrderCode = f.OrderCode,
            //                      Total = f.Total
            //                  };
            // var orderInfo = (from s in skuInfo
            //                  group s by new { s.CommodityId }
            //                 into l
            //                  select new
            //                  {
            //                      Id = l.Key.CommodityId,
            //                  }).ToList();
            // var orderInfoList = new List<string>();
            // foreach (var item in orderInfo)
            // {
            //     foreach (var items in orderInfos)
            //     {

            //     }
            // }





            var commodityCount = (from commodity in commodityDetails
                                  group commodity by new { commodity.CommodityId }
                    into ct
                                  select new { CommodityId = ct.Key.CommodityId }).ToList();

            var commodityProperty = _commodityProperty.Table.Where(c => c.IsDeleted == false);
            var commodityPropertyValue = _commodityPropertyValue.Table.Where(p => p.IsDeleted == false);
            var Info = new List<object>();

            var commodityPropertyValueSkus = from cvs in commodityDetails
                                             join c in _commodity.Table on cvs.CommodityId equals c.Id

                                             join pv in _commodityPropertyValue.Table on cvs.CommodityPropertyValueId equals pv.Id
                                             select new
                                             {
                                                 Id = cvs.Id,
                                                 CommodityId = cvs.CommodityId,
                                                 ProductName = c.ProductName,
                                                 Price = c.Price,
                                                 CoverPictrue = c.CoverPicture,
                                                 CommodityPropertyValueId = cvs.CommodityPropertyValueId,
                                                 CommodityProperty = cvs.CommodityPropertyId,
                                                 PropertyValue = pv.PropertyValue
                                             };

            var shoppingModelList = new List<ShoppingModel>();
            foreach (var comd in commodityCount)
            {
                var CommodityProductValueStr = "";
                var ProductName = "";
                var CoverPictrue = "";
                var Price = 0.0;

                foreach (var item in commodityPropertyValueSkus)
                {
                    if (comd.CommodityId == item.CommodityId)
                    {

                        ProductName = item.ProductName;
                        Price = item.Price;
                        CoverPictrue = item.CoverPictrue;
                        CommodityProductValueStr += item.PropertyValue + " ";
                    }
                }
                shoppingModelList.Add(new ShoppingModel
                {
                    CommodityId = comd.CommodityId,
                    ProductName = ProductName,
                    Price = Price,
                    CoverPictrue = CoverPictrue,
                    CommodityProductValueStr = CommodityProductValueStr,

                });
            }



          

            return JsonHelper.Serialize(new
            {
                Code = 200,
                Data = new
                {
                    orderInfo = _userOrder.Table.Where(uo => uo.UsersId == int.Parse(userid)),
                    shoppingModelList
                },
                Msg = "获取订单成功！"
            });


        }












    }
}